package com.gxf.drugmg.controller;

import com.gxf.drugmg.entity.Drug;
import com.gxf.drugmg.service.DrugService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/drugs")
@CrossOrigin(origins = "*")
public class DrugController {
    
    @Autowired
    private DrugService drugService;
    
    @GetMapping
    public ResponseEntity<List<Drug>> getAllDrugs() {
        List<Drug> drugs = drugService.getAllDrugs();
        return ResponseEntity.ok(drugs);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Drug> getDrugById(@PathVariable Long id) {
        Drug drug = drugService.getDrugById(id);
        if (drug != null) {
            return ResponseEntity.ok(drug);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @PostMapping
    public ResponseEntity<Drug> createDrug(@RequestBody Drug drug) {
        Drug savedDrug = drugService.saveDrug(drug);
        return ResponseEntity.ok(savedDrug);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Drug> updateDrug(@PathVariable Long id, @RequestBody Drug drug) {
        drug.setId(id);
        Drug updatedDrug = drugService.saveDrug(drug);
        return ResponseEntity.ok(updatedDrug);
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDrug(@PathVariable Long id) {
        drugService.deleteDrug(id);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/search")
    public ResponseEntity<List<Drug>> searchDrugs(@RequestParam String name) {
        List<Drug> drugs = drugService.searchDrugsByName(name);
        return ResponseEntity.ok(drugs);
    }
}